﻿module Sustainalytics.Portfolio {
    import Common = Sustainalytics.Common;

    export class PortfolioCompanyService implements IPortfolioCompanyService {

        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private notificationFactory: Common.INotificationFactory;
        private staticObjects: Common.IStaticObjects;
        private urlBase: string;

        // Ctor.
        public constructor($q: ng.IQService, $http: ng.IHttpService, notificationFactory: Common.INotificationFactory, staticObjects: Common.IStaticObjects) {
            this.$q = $q;
            this.$http = $http;
            this.notificationFactory = notificationFactory;
            this.urlBase = staticObjects.portfolioBaseUrl;
            this.staticObjects = staticObjects;
        }

        // show error message for a given error code
        private showError(err) {
            var ctx = this;
            if (err && err['errorCode']) {

                ctx.notificationFactory.error('', ctx.staticObjects.getErrorMesageByStatusCode(err, err['errorCode']));
            }
        }

        private showInformation(inf) {
            var ctx = this;
            if (inf && inf['code'])
                ctx.notificationFactory.success("The company is in the selected portfolio!");
        }

        // get paged list of portfolio
        public getPortfolioCompanies(filter: PortfolioCompanyFilterDto, skip: number, take: number, orderBy: string[], orderByAsc: boolean, userId: string) {
            var def = this.$q.defer();
            var ctx = this;
            var options = new Common.ListOptions();
            options.skip = skip;
            options.take = take;
            options.orderBy = orderBy;
            options.orderAscending = orderByAsc;
            options.includeAllFields = true;
            options.getCount = true;

            var params = $.param({
                userId: userId,
                listOptions: options
            });

            var url = ctx.urlBase + "/api/v1/portfolios/" + filter.portfolioId + "/details?" + params;
            var promise = ctx.$http.get(url);

            promise.success(
                data => {
                    def.resolve(data);
                }).error(
                err => {
                    ctx.showError(err);
                    def.reject();
                });

            return def.promise;
        }

        public addSecurityToMatched(portfolioName: string, portfolioMatchId: string) {
            var url = this.urlBase + "/api/v1/portfolios/" + portfolioName + "/matches/" + portfolioMatchId;

            return this.$http.put(url, null);
        }

        public deleteSelectedMatches(portfolioName: string, portfolioMatchIds: string[]) {
            var url = this.urlBase + "/api/v1/portfolios/" + portfolioName + "/matches/deleteSelectedMatches";
            var httpConfig = { method: "PUT", url: url, data: { portfolioMatchIds: portfolioMatchIds } }; 

            return this.$http(httpConfig);
        }

        public addCompanyToPortfolioMatches(portfolioName: string, companyId: string) {
            var url = this.urlBase + "/api/v1/portfolios/" + portfolioName + "/matches/addCompany/" + companyId;
            var httpConfig = { method: "POST", url: url, data: null };

            return this.$http(httpConfig);
        }


        public deletePortfolioMatches(portfolioName: string) {
            var url = this.urlBase + "/api/v1/portfolios/" + portfolioName + "/matches/deleteAllMatches";

            return this.$http.delete(url);
        }

        public renamePortfolioMatches(portfolioName: string, newPortfolioName: string) {
            var url = this.urlBase + "/api/v1/portfolios/" + portfolioName + "/matches/renamePortfolioMatches/" + newPortfolioName;

            return this.$http.post(url,null);
        }

        //public updateSecurityWeight(portfolioMatchid: string, newValue: number) {
        //    var url = this.urlBase + '/api/v1/portfolios/UpdateSecurityWeight?portfolioMatchid=' + portfolioMatchid + '&newWeightValue=' + newValue;
        //    return this.$http.post(url, null);
        //}

        public getValidPortfolioMatches(portfolioName: string, skip: number, take: number, orderBy: string[], orderByAsc: boolean) {
            var options = new Common.ListOptions();
            options.skip = skip;
            options.take = take;
            options.orderBy = orderBy;
            options.orderAscending = orderByAsc;
            options.includeAllFields = true;
            options.getCount = true;

            var params = $.param({
                listOptions: options
            });

            var url = this.urlBase + "/api/v1/portfolios/" + portfolioName + "/matches/valid?" + params;

            var promise = this.$http.get(url);

            return promise;
        }

        public getInvalidPortfolioMatches(portfolioName: string, skip: number, take: number, orderBy: string[], orderByAsc: boolean) {
            var options = new Common.ListOptions();
            options.skip = skip;
            options.take = take;
            options.orderBy = orderBy;
            options.orderAscending = orderByAsc;
            options.includeAllFields = true;
            options.getCount = true;

            var params = $.param({
                listOptions: options
            });

            var url = this.urlBase + "/api/v1/portfolios/" + portfolioName + "/matches/invalid?" + params;

            var promise = this.$http.get(url);

            return promise;
        }

        //deletePortfolio
        public deletePortfolioCompany(id: string, portfolioId: string) {
            var ctx = this;
            var def = this.$q.defer();

            var url: string = this.urlBase + '/api/v1/portfolios/' + portfolioId + '/details/' + id;

            var promise: ng.IHttpPromise<{}> = this.$http['delete'](url);



            promise.success(function (data) {
                //ctx.showMessage("Portfolio deleted successfully!");
                def.resolve(data);
            })
                .error(function (err) {
                    ctx.showError(err);
                    def.reject();
                })
            return def.promise;
        }

        //post PortfolioCompany
        public insertPortfolioCompany(id: string, portfolioId: string) {
            var ctx = this;
            var def = this.$q.defer();

            var url: string = this.urlBase + '/api/v1/portfolios/' + portfolioId + '/details/' + id;

            var promise: ng.IHttpPromise<{}> = this.$http.post(url, null);

            promise.success(function (data) {
                if (data) {
                    if (data['warningCode'] === 5103) {
                        ctx.notificationFactory.warn(ctx.staticObjects.getErrorMesageByStatusCode(data['warningCode'], data));
                        ctx.notificationFactory.success("Succesfully added");
                    }
                    if (data['warningCode'] === 5105) {
                        ctx.notificationFactory.error('', ctx.staticObjects.getErrorMesageByStatusCode(data['warningCode'], data));
                    }
                }
                if (data === "") {
                    ctx.notificationFactory.success("Succesfully added");
                }
                def.resolve(data);
            })
                .error(err => {
                    if (err['errorCode']) {

                        var msg = ctx.staticObjects.getMessageByInternalCode(err['errorCode']);
                        ctx.notificationFactory.error('', msg);
                    } else {
                        ctx.showError(err);
                    }
                    def.reject();
                });
            return def.promise;
        }
    }


    // register service with Portfolio Angular module
    angular.module(portfolioModuleName).service('PortfolioCompanyService',
        ['$q', '$http', 'notificationFactory', 'staticObjects', PortfolioCompanyService]);
}
